//
//  MoViewTip.swift
//  xmall
//
//  Created by zhuxietong on 2020/2/19.
//  Copyright © 2020 xmall. All rights reserved.
//

import Foundation
import soapp
import Eelay


open class MoPluginTip:MoTip{


//    open override func updateAction(action:Action) {
//        switch action {
//        case .dismiss:
//            break
//        case .loading(message: let msg):
//            messageN.attributedText = (msg ?? "").ui.font13.color(color: ._foreground).center.astring
//            break
//        case .tip(message: let msg, title: let title, action: let bt):
//            messageN.attributedText = msg.ui.font13.color(color: ._foreground).center.astring
//            titleN.attributedText = (title ?? "").ui.bfont16.color(color: ._foreground).center.astring
//            if let b = bt{
//                _ = buttonN.ui.font(size:13).ncolor(color: ._foreground).buttonColor(color: .color(light: "#333", dark: "2222")).padding(insets: [6,36]).ntitle(title: b.0).corner4
//                buttonAction = b.1
//            }
//        }
//    }
//            
//      
            

}



open class MoViewTip: NSObject {
    
    public var insets:UIEdgeInsets = UIEdgeInsets.zero
    public var createNodeBlock:()->MoTip = {
        return TLiveLoading()
    }
    
    public var action:MoTip.Action = .dismiss
    public var _node:MoTip? = nil
    public var tipNode:MoTip{
        get{
            guard let n = _node else {
                let node = self.createNodeBlock()
                _node = node
                return node
            }
            return n
        }
    }
    
    public override init() {
        super.init()
        self.backView.backgroundColor = ._background
    }
    
    public var constrains = [NSLayoutConstraint]()
    public let backView = UIView()
    
    public let blur:UIVisualEffectView = {
        return UIVisualEffectView(effect: UIBlurEffect.init(style: .prominent))
    }()
    
    public var backgroundColor:UIColor?{
        set{
            backView.backgroundColor = newValue
        }
        get{
            return backView.backgroundColor
        }
    }

    public weak var superView:UIView?{
        didSet{
            let node = tipNode.view
            backView.eelay = [
                [blur,[ee.T.L.B.R]],
                [node,[ee.T.L.B.R.safe]]
            ]
            node.backgroundColor = .clear
            moveToSuperView()
            removeFromSuperView()
        }
    }
    
    public func moveToSuperView() {
        guard let sv = superView else {
            return
        }
        if let _ = self.backView.superview{
            return
        }
       
        constrains = sv.setEeLays(lays: [[backView,[ee.T.L.B.R,[insets.top.+1000,insets.left.+1000,(-insets.bottom).+1000,(-insets.right).+1000]]]]).1
    }
       
       public func removeFromSuperView(){
           guard let sv = superView else {
               return
           }
           self.backView.removeFromSuperview()
           sv.removeConstraints(constrains)
        }
        public var buttonAcation:()->Void = {}
    public func `do`(action:MoTip.Action,animated:Bool=true) {
            tipNode.action = action
            buttonAcation = {}
            switch action {
            case .dismiss:
                self.action = action
                UIView.beginAnimations(nil, context: nil)
                UIView.setAnimationDuration(0.16)
                UIView.setAnimationCurve(.easeIn)
                backView.alpha = 0
                UIView.commitAnimations()
                co_delay(delay: 0.16) {[weak self] in
                    self?.removeFromSuperView()
                }
                return
                
            case .loading,.tip:
//                print("_sss__OOOOSOSISi---\(action)")
                moveToSuperView()
                self.action = action
            }
            
//        if(animated){
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(0.16)
            UIView.setAnimationCurve(.easeIn)
//            loading.setNeedsLayout()
//            loading.layoutIfNeeded()
            backView.alpha = 1
            UIView.commitAnimations()
//        }
    }
}


open class MoTip:MoDisplayNode{
//    UIActivityIndicatorView(style:UIActivityIndicatorView.Style.white)
    public var indicatorN = ASDisplayNode { () -> UIView in
        return UIActivityIndicatorView(style: MoTheme.global.mode.indicatorStyle)
    }
    public let messageN = ASTextNode2()
    public let titleN = ASTextNode2()
    public let buttonN = ASButtonNode()
    public var buttonAction:()->Void = {}

    
  
    
    open override func addLayoutRules() {
        buttonN.addTarget(self, action: #selector(pressedBt), forControlEvents: .touchUpInside)
    }
    
    public var action:MoTip.Action = .dismiss
    {
        didSet{
            switch action {
            case .dismiss:
                (indicatorN.view as? UIActivityIndicatorView)?.stopAnimating()
            case .loading:
                (indicatorN.view as? UIActivityIndicatorView)?.startAnimating()
            case .tip(message: _, title: _, action: let ac):
                if let a = ac{
                    buttonAction = a.1
                }
                (indicatorN.view as? UIActivityIndicatorView)?.stopAnimating()
            }
            updateAction(action: action)
//                UIView.beginAnimations(nil, context: nil)
//                UIView.setAnimationDuration(0.2)
//                UIView.setAnimationCurve(.easeIn)
            setNeedsLayout()
            layoutIfNeeded()
//                UIView.commitAnimations()
        }
    }
    open func updateAction(action:Action) {
        switch action {
        case .dismiss:
            break
        case .loading(message: let msg):
            messageN.attributedText = (msg ?? "").ui.font14.color(color: ._foreground).center.astring
            break
        case .tip(message: let msg, title: let title, action: let bt):
            messageN.attributedText = msg.ui.font14.color(color: ._foreground).center.astring
            titleN.attributedText = (title ?? "").ui.bfont16.color(color: ._foreground).center.astring
            if let b = bt{
                _ = buttonN.ui.font(size:13).ncolor(color: ._foreground).padding(insets: [6,36]).ntitle(title: b.0).buttonColor(color: .color(light: "#aaa9", dark: "#fff3")).corner4
                buttonAction = b.1
            }
        }
    }
            
      
    @objc func pressedBt(){
        buttonAction()
    }
    

}

class TLiveLoading: MoTip {
    
    
    let backgrondN = ASImageNode()
    let blankN = ASDisplayNode()
    let closeBt = ASButtonNode()

    var quit:()->Void = {}
    
    

    override func addLayoutRules() {
        super.addLayoutRules()
        closeBt.imageNode.contentMode = .scaleAspectFit
        closeBt.ui.nimage(UIImage(named: "live-set-cancel-n"))

        closeBt.addTarget(self, action: #selector(quiteAction), forControlEvents: .touchUpInside)
    }
    @objc func quiteAction() {
        quit()
    }
    
    
    
                
    override func specGetter() -> _Spec {
        var items:[_Spec] = []
        switch action {
        case .dismiss:
            items.append(blankN[0])
        case .loading(message:_):
            items.append(.stack(["h",_justfy(.center)], childs: [indicatorN["40",40]]))
            items.append(messageN.Spec)
        case .tip(message:_, title: let title, action: let bt):
            if let _ = title{
                items.append(titleN.Spec)
            }
            items.append(messageN.Spec)
            if let _ = bt{
                items.append(.stack(["h",_justfy(.center)], childs: [buttonN.Spec]))
            }
        }
        
        
        let spec:_Spec = .inset([], [20], child: .stack(["v|8",_justfy(.center),&-.stretch], childs: items))
        
        return spec.addOver(.stack(["v|16",&-.stretch], childs: [
            .stack([_grow(1),_shrink(1)], childs: []),
            .stack(["h",_justfy(.center),], childs: [closeBt["30",30]]),
            .stack([_grow(0),_shrink(0),"20"], childs: []),
        ]))
    }
    
}


extension MoTip{
    public typealias TouchUpInside = ()->Void
    public typealias ButtonAction = (String,TouchUpInside)
      
    public enum Action {
        case loading(message:String?)
        case dismiss
        case tip(message:String,title:String?,action:ButtonAction?)
    }
    

}
